<template>
    <div v-show="visible" ref="watermarkEl" class="watermark-container"></div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount, computed } from 'vue'

const props = defineProps({
    config: {
        type: Object,
        default: () => ({
            text: '默认水印',
            opacity: 0.1,
            fontSize: 24,
            color: '#000'
        })
    }
})

const visible = ref(true)
const watermarkEl = ref(null)

// 如果 color 是对象，则取 hex，否则直接使用
const normalizedColor = computed(() => {
    return typeof props.config.color === 'object' && props.config.color.hex
        ? props.config.color.hex
        : props.config.color
})

const updateWatermark = () => {
    const { text, opacity, fontSize } = props.config
    const color = normalizedColor.value

    const canvas = document.createElement('canvas')
    canvas.width = 300
    canvas.height = 200
    const ctx = canvas.getContext('2d')

    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.globalAlpha = opacity
    ctx.font = `${fontSize}px Arial`
    ctx.fillStyle = color
    ctx.rotate(-20 * Math.PI / 180)
    ctx.fillText(text, 50, 150)

    const base64Url = canvas.toDataURL()

    if (watermarkEl.value) {
        watermarkEl.value.style.backgroundImage = `url(${base64Url})`
        watermarkEl.value.style.backgroundRepeat = 'repeat'
    }
}

// 监听具体依赖的变化：文本、透明度、字体大小及颜色
watch(
    () => [props.config.text, props.config.opacity, props.config.fontSize, normalizedColor.value],
    updateWatermark
)

onMounted(updateWatermark)
onBeforeUnmount(() => {
    if (watermarkEl.value) {
        watermarkEl.value.style.backgroundImage = ''
    }
})
</script>

<style scoped>
.watermark-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 9999;
}
</style>
